/*

    thermcap the thermal data collector program.
    thermcap collects CPU heating data and stores it in a csv and svg-graphic file
    Copyright (C) 2011  Giovanni Santostefano

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


#include <string.h>
#include "thermal_cap.h"

/*get the CPU temperature*/
int get_cpu_therm(char *cpuproc)
{
	char tempstr[2048];
	char tempnum[2048];
	char flag=0;
	int i=0;
	int j=0;
	FILE *tempstream=NULL;
	
	if(!cpuproc) return -1;
		
	memset((void*)tempstr,0,2048);
	memset((void*)tempnum,0,2048);
	
	/*open the proc temperature file and get the temperature string*/
	if(!(tempstream=fopen(cpuproc, "r"))) return -1;
	
	fgets(tempstr, 2047,tempstream);
	fclose(tempstream);
	
	/*insulate the temperature value and convert into int*/
	for(i=0; i<2048 && flag!=2; i++)
	{
		if(tempstr[i]>='0' && tempstr[i]<='9')
		{
			flag=1;
			tempnum[j]=tempstr[i];
			j++;
		}
		
		if((tempstr[i]<'0' || tempstr[i]>'9') && flag==1)
		{
			flag=2;
		}
	}
	
	return atoi(tempnum);
}


/*Thermal capture data function*/
int thermal_cap(char *filename, char *cpu1fname)
{
	/*char *cpu1proc="/proc/acpi/thermal_zone/CPUZ/temperature\0";*/
	/*char *cpu2proc="/proc/acpi/thermal_zone/GFXZ/temperature\0";*/
	int cputemp=0;
	int gputemp=0;
	
	FILE *stream=NULL;
	
	if(!filename) return -1;
	
	if(!(stream=fopen(filename, "a+"))) return -1;
	
	cputemp=get_cpu_therm(cpu1fname);
	
	if(cputemp<0)return -2;

	fprintf(stream,"%d\n",cputemp);
	
	fclose(stream);
	
	return 0;
}

